from querier.esquerier import ElasticSearchQuerier
import utils.utils as utils
import math

WORDCLOUD_TOP_N = 100
MINIMUM_SHOULD_MATCH = "5<85% 10<9"
QUERY_SIZE = 1


class Class1WordCloudMatchQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type):
        super(Class1WordCloudMatchQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type

    def _build_query(self, args):
        class1_name = args.get('class1_name', None)
        query_keywords = args.get('term', None)
        from_ = args.get('from', 0)
        from_ = from_ if from_ else 0
        size_ = args.get('size', 10)
        size_ = size_ if size_ else 10
        query = self._genQuery(class1_name, query_keywords, from_, size_)
        return query, {}, {'class1_name': class1_name, 'query_keywords': query_keywords}

    def _build_result(self, es_result, param):
        class1_name = param['class1_name']
        query_keywords = param['query_keywords']
        posts = []
        for hit in es_result['hits']['hits']:
            posts.append(extractResult(hit))
        return {
            'wordcloud': posts

        }

    def _genQuery(self, class1_name, query_keywords, from_, size_):
        should_clause = []
        if class1_name:
            should_clause.append(
                {
                    "match": {
                        "class1_name":
                            {"query": class1_name,
                             "minimum_should_match": MINIMUM_SHOULD_MATCH
                             }
                    }
                }
            )
        if query_keywords:
            should_clause.append(
                {
                    'query_string': {
                        'query': query_keywords,
                        'fields': ['class1_name', 'keywords'],
                        'minimum_should_match': MINIMUM_SHOULD_MATCH
                    }
                }
            )
        query = {
            "from": from_,
            "size": size_,
            "query": {
                "bool": {
                    "should": should_clause
                }
            }
        }

        return query


def extractResult(hit):
    source_ = hit['_source']
    return {
        "class1_id": source_['class1_id'],
        "class1_name": source_['class1_name'],
        'keywords': source_['keywords'][0:WORDCLOUD_TOP_N],
        'weight': source_['weight'][0:WORDCLOUD_TOP_N],
    }
